﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;

namespace MySerial.Class_Serial
{
    public class Serial_Set
    {
        //static string[] _str_Serial;
        ///// <summary>
        ///// 返回本机所有串口号
        ///// </summary>
        ///// <returns></returns>
        //public static string[] Get_Serial()
        //{
        //    _str_Serial= System.IO.Ports.SerialPort.GetPortNames();
        //    return _str_Serial;
        //}
        ///// <summary>
        ///// 添加串口号到ComboBox中
        ///// </summary>
        ///// <param name="cbx">控件</param>
        ///// <returns>已有串口数</returns>
        //public static int Set_Cbx_Serial(ComboBox cbx)
        //{
        //    cbx.Items.Clear();
        //    foreach (string s in _str_Serial)
        //    {
        //        cbx.Items.Add(s);
        //    }
        //    return _str_Serial.Length;
        //}


        /// <summary>
        /// 获取串口号
        /// </summary>
        /// <returns>串口类型组</returns>
        public static List<Serial_Info> GetPorts()
        {
            List<Serial_Info> back = new List<Serial_Info>();
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity")) //调用WMI，获取Win32_PnPEntity，即所有设备
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if ((hardInfo.Properties["Name"].Value != null) &&
                        (hardInfo.Properties["Name"].Value.ToString().Contains("COM"))&&
                        (hardInfo.Properties["Name"].Value.ToString().ToUpper().Contains("USB"))) //筛选出名称中包含COM的
                    {
                        Serial_Info temp = new Serial_Info();
                        string s = hardInfo.Properties["Name"].Value.ToString(); //获取名称
                        int p = s.IndexOf('(');
                        temp.Des = s.Substring(0, p); //截取描述（名称）
                        temp.Name = s.Substring(p + 1, s.Length - p - 2); //截取串口号
                        back.Add(temp);
                    }
                }
                searcher.Dispose();
            }
            return back;
        }


    }
}
